package com.ktjiaoyu.springsecuritydemo.config;

import com.ktjiaoyu.springsecuritydemo.handler.MyAccessDeniedHandler;
import com.ktjiaoyu.springsecuritydemo.handler.MyAuthenticationFailureHandler;
import com.ktjiaoyu.springsecuritydemo.handler.MyAuthenticationSuccessHandler;
import com.ktjiaoyu.springsecuritydemo.service.UserDetailsServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    UserDetailsServiceImpl userDetailsServiceImpl;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //配置自定义登录页面
        http.formLogin()
                .usernameParameter("usrName")
                .passwordParameter("usrPassword")
                //指定登录页面
                .loginPage("/tologin")
                //指定登录地址
                .loginProcessingUrl("/doLogin")
//                //指定登录成功跳转页面
                .successForwardUrl("/toMain")
                .failureForwardUrl("/toError");
//            .successHandler(new MyAuthenticationSuccessHandler("http://www.baidu.com"))
//        .failureHandler(new MyAuthenticationFailureHandler("http://www.jd.com"));

        //授权
        http.authorizeRequests()
                //指定/toLogin不需要登录即可访问
                .antMatchers("/tologin").permitAll()
//                .antMatchers("/css/**","/js/**","/images/**").permitAll()
                .regexMatchers(".+[.]css",".+[.]js").permitAll()
                //指定/toMain1路劲只有拥有admin权限的用户才能访问
//                .antMatchers("/toMain1").hasAuthority("admin123")
//                .antMatchers("/toMain1").hasAnyAuthority("admin123","admin")
//                .antMatchers("/toMain1").hasRole("abcd")
//                .antMatchers("/toMain1").hasAnyRole("abc","abcd")
//                .antMatchers("/toMain1").hasIpAddress("127.0.0.1")
                .antMatchers("/toMain1").access("hasAuthority('admin')")
                //除了上面指定的路劲其他的都需要登录才能访问
                .anyRequest().authenticated();


        //关闭防火墙
        http.csrf().disable();
        //自定义403错误处理
        http.exceptionHandling().accessDeniedHandler(new MyAccessDeniedHandler());

        //记住我的配置
        http.rememberMe()
                .tokenValiditySeconds(60)
                .userDetailsService(userDetailsServiceImpl)
                .tokenRepository(persistentTokenRepository());

        //退出
        http.logout().logoutSuccessUrl("/tologin");
    }

    @Resource
    DataSource dataSource;

    @Bean
    public PersistentTokenRepository persistentTokenRepository(){
        JdbcTokenRepositoryImpl p=new JdbcTokenRepositoryImpl();
        p.setDataSource(dataSource);
//        p.setCreateTableOnStartup(true);
        return p;
    }
}
